package com.youzan.cloud.biz.integral.usercase;
import com.alibaba.fastjson.JSONObject;
import com.youzan.cloud.biz.integral.common.CommandHandler;
import com.youzan.cloud.biz.integral.common.UserCommand;
import com.youzan.cloud.biz.integral.extension.LinkerExtensionPoints;
import com.youzan.cloud.biz.integral.model.PointQueryLogCmd;
import com.youzan.cloud.biz.integral.model.request.PointLogQueryRequest;
import com.youzan.cloud.component.retry.annotation.Retry;
import com.youzan.cloud.connect.service.sdk.ConnectServiceResponse;
import com.youzan.cloud.connect.service.sdk.exception.ConnectServiceCallException;
import com.youzan.cloud.connector.component.dto.member.PointLogListQueryRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
 * @author wangyuan
 * @version 1.0
 * @description: TODO
 * @date 2021/8/23 15:01
 */
@Component
@CommandHandler(responseFor = PointQueryLogCmd.class)
public class QueryPointsLogUserCase extends AbstractPointUserCase<PointQueryLogCmd> {
    private static final Logger log = LoggerFactory.getLogger(QueryPointsLogUserCase.class);

    @Override
    public Boolean exec(UserCommand param) throws Exception {
        // force cast
        PointQueryLogCmd cmd = (PointQueryLogCmd)param;

        log.info("start exec query point log user case, {}", JSONObject.toJSONString(cmd));

        cmd.setStatus(UserCommand.ExecStatus.EXECUTING);

        PointLogQueryRequest request =  PointLogQueryRequest.builder()
                .pageNo(cmd.getPage())
                .pageSize(cmd.getPageSize())
                .mobile(cmd.getMobile())
                .createdTimeStart(cmd.getStartTime())
                .createdTimeEnd(cmd.getEndTime())
                .type(cmd.getType())
                .extendMap(cmd.getExtParams())
                .build();
        // write serials log

        // call connector
        ConnectServiceResponse<?> response = syncQueryPointCaseToOutSystem(cmd.getId(), request);

        if(null == response || !response.isSuccess()) {
            cmd.setStatus(UserCommand.ExecStatus.FAILED);

        } else {
            cmd.setStatus(UserCommand.ExecStatus.DONE);
            cmd.setResult(response.getResponseDTO());


        }
        return true;
    }

    @Retry(bizCase = "QueryPointsLogUserCase", uniqKey = "id")
    public ConnectServiceResponse<?>  syncQueryPointCaseToOutSystem(String id, PointLogQueryRequest request) throws ConnectServiceCallException {

        log.info("SEND_POINT_LOG_DATA - {}  started", id);
        // call connector
        ConnectServiceResponse<?> response = callLinker(LinkerExtensionPoints.SEND_POINT_LOG_DATA, request);
        log.info("SEND_POINT_LOG_DATA - {} finished, result= {}, {}", id, response.isSuccess(), response.getErrMsg());

        return  response;
    }
}
